<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.js"></script>
</head>
<h1>axios请求按钮</h1>
<input type="text" id="ipt">
<button id="btnGet">发送请求</button>


<body>
    <script>
        // 先创建一个axios实例 axios.create  参数为请求的配置 baseURL Timeout headers
        // 给axios添加请求，get请求的参数是接口，配置对象，post请求的参数是接口，请求数据（body），配置对象，
        // 给axios设置请求拦截，响应拦截
        // 取消请求
        const oBtn = document.getElementById('btnGet')
        const oIpt = document.getElementById('ipt')
        const myAxios = axios.create({
            baseURL: 'http://127.0.0.1:5500',
            Timeout: 10000,
            headers: {
                token: "asjdlakjdalsdjasld"
            }
        })
        myAxios.interceptors.request.use((config)=>{
            NProgress.start() 
            // 判断输入框是为空
            if (!oIpt.value) {
            // 为空停止请求发送，未写
               return alert('输入框不能为空');
            }
            return config
        },(e)=>{
            return Promise.reject(e)
        })
        myAxios.interceptors.response.use((response)=>{
            NProgress.done()
            if (!response.data) {
            return alert('请输入正确的序列号');
            }
            return response.data
        },(e)=>{
            return Promise.reject(e)
        })
      
        oBtn.onclick = async function() {
            try {
                const re = await myAxios.get('http://127.0.0.1:9000/user', {
                    params: {
                        userID: oIpt.value
                    },
                })
                console.log(re)
            } catch (error) {
                console.log(error)
            }
           
        }
    </script>
</body>

</html>